<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\videomaterial;

use app\common\lib\Common;
use app\common\lib\Constant;
use app\common\lib\Guzzle;
use app\common\lib\Puppeteer;
use app\common\lib\RedisQueue;
use app\common\lib\TencentAsr;
use app\common\lib\TencentIvld;
use app\exception\IndexException;
use app\model\material\MaterialDataModel;
use app\model\material\MaterialVideoAnalyzeLogModel;
use app\model\redis\RedisQueueModel;
use app\model\user\UserPromotionVideoModel;
use app\model\video\AsyncUploadVideoIvldModel;
use app\model\video\VideoAnalyzeLogModel;
use JamesHeinrich\GetID3\GetID3;
use support\Cache;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class AsyncVideoMaterial  implements Consumer
{
    // 要消费的队列名
    public $queue = 'asyncVideoMaterial';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try{

            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (\Throwable $e){
            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }
    }

    protected function handle($data)
    {
        $first = MaterialDataModel::getInstance()->find($data['materialid']);
        $first->queue_status = 1;
        $first->save();

        $videoData = json_decode($first['orig_heigh_video_data'], true);
        if($videoData){
            list($videos,$totalTts) = $this->getVideoData($videoData);
            //file_put_contents(runtime_path('heigh_video_data.log'),json_encode($videos,256)."\n",8);
            $first->heigh_video_data = json_encode($videos,256);
            $first->heigh_video_tts = $totalTts;
            $first->heigh_video_nums = count($videos);
        }

        $videoData2 = json_decode($first['orig_normal_video_data'], true);
        if($videoData2){
            list($videos,$totalTts) = $this->getVideoData($videoData2);
            //file_put_contents(runtime_path('normal_video_data.log'),json_encode($videos,256)."\n",8);
            $first->normal_video_data = json_encode($videos,256);
            $first->normal_video_tts = $totalTts;
            $first->normal_video_nums = count($videos);
        }
        //file_put_contents(runtime_path('heigh_video_data_save.log'),json_encode($first->heigh_video_data,256)."\n",8);
        //file_put_contents(runtime_path('normal_video_data_save.log'),json_encode($first->normal_video_data,256)."\n",8);
        $first->queue_status = 2;
        $first->save();


        return ['success'];
    }

    protected function getVideoData($videoData)
    {
        $withHeightMap = [];
        foreach (Constant::OVERSEA_VIDEO_RATE_MAP as $rate=>$val){
            $withHeightMap['rate_'.$val] = $rate;
        }

        //获取视频数据
        $totalTts = 0;
        $videos = [];
        foreach($videoData as $k=>$video){
            $first = MaterialVideoAnalyzeLogModel::getInstance()->getWhere(['video_code'=>md5($video['video'])])->first();
            if($first){
                $video['id'] = ($k+1);
                $video['tts'] = $first['tts'];
                $video['width'] = $first['width'];
                $video['height'] = $first['height'];
                $video['video_scale'] = $first['video_scale'];
                //没有对应分辨率就过滤掉
                if(empty($video['video_scale'])){
                    //continue;
                }

                if ($video['height']<= 1920 && $video['height']>=1080 && $video['width']<=1920 &&$video['width']>=1080) {
                    $totalTts = round($totalTts+$video['tts']);
                    $videos[] = $video;
                }
            }else{
                try{
                    $video['id'] = ($k+1);
                    $fullPath = runtime_path(Common::getRequestId().'.mp4');
                    file_put_contents($fullPath,file_get_contents($video['video']));
                    $voiceRe= (new GetID3())->analyze($fullPath);
                    unlink($fullPath);
                    if(!empty($voiceRe['playtime_seconds'])){

                        $width = $voiceRe['video']['resolution_x']??0;
                        $height = $voiceRe['video']['resolution_y']??0;
                        $rateKey = $height>0 && $width>0 ? round($width/$height,2):0;

                        $video['tts'] = floor($voiceRe['playtime_seconds']??'0');
                        $video['width'] = $width;
                        $video['height'] = $height;
                        $video['video_scale'] = $withHeightMap['rate_'.$rateKey]??'';

                        //保存解析记录
                        $insert = [
                            'video'=>$video['video'],
                            'tts'=>$video['tts'],
                            'width'=>$video['width'],
                            'height'=>$video['height'],
                            'video_scale'=>$video['video_scale'],
                            'video_code'=>md5($video['video']),
                            'size'=>!empty($voiceRe['filesize'])?round($voiceRe['filesize']/1024/1024,1):0.0,
                        ];
                        MaterialVideoAnalyzeLogModel::getInstance()->insertGetId($insert);

                        //没有对应分辨率就过滤掉
                        if(empty($video['video_scale'])){
                            //continue;
                        }

                        if ($video['height']<= 1920 && $video['height']>=1080 && $video['width']<=1920 &&$video['width']>=1080) {
                            $totalTts = round($totalTts+$video['tts']);
                            $videos[] = $video;
                        }
                    }
                }catch (\Throwable $e){}
            }
        }

        return [$videos, $totalTts];
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}